import { defineStore } from 'pinia'
import { getMenu } from '@/api/admin'
import { type menuDataInfo } from '@/page/types/admin/menu'
import router from '@/router/router'
import { type RouteRecordRaw } from 'vue-router'

export const menuStore = defineStore('menuStore', {
  actions: {
    async toSetMenu() {
      await getMenu().then(res => {
        if (!res || !res.data || res.data.length === 0) {
          return
        }
        const data: menuDataInfo[] = res.data || []
        const modules = import.meta.glob('../page/home/main/**/*.vue')
        data.forEach(das => {
          const childrenRouter = [] as RouteRecordRaw[]
          let url = ''
          if (das.multiUrl) {
            url = '../page/home/main' + das.multiUrl + '.vue'
          }
          let dasList = [] as string[]
          if (das.children && das.children.length > 0) {
            dasList = das.children.map(element => element.permission)
            das.children.forEach(child => {
              let urlChild = ''
              if (child.multiUrl) {
                urlChild = '../page/home/main' + child.multiUrl + '.vue'
              }
              let childList = [] as string[]
              if (child.children) {
                childList = child.children.map(element => element.permission)
              }
              childrenRouter.push({
                path: child.multiUrl,
                name: child.name,
                component: modules[`${urlChild}`],
                meta: {
                  header: child.name,
                  buttons: childList,
                  type: child.menuType,
                  icon: child.icon
                }
              })
            })
          }
          router.addRoute('home', {
            path: das.multiUrl,
            name: das.name,
            component: modules[`${url}`],
            children: childrenRouter,
            meta: {
              header: das.name,
              buttons: dasList,
              type: das.menuType,
              icon: das.icon
            }
          })
        })
      })
    }
  },
  persist: false
})
